<template>
  <div class="flex-column">
    <a-modal v-model:visible="tableVisible"
             :title="tableModalTitle"
             width="1200px"
             :mask-closable="false"
             class="curd-modal"
             :get-container="getModalContainer"
    >
      <render :data="tableModalRender" @success="onLoadTable(tableTreeNode)"></render>
      <template #footer>
        <render v-if="tableModalRender" :data="tableModalRender.footer"></render>
      </template>
    </a-modal>
    <div style="margin:0 10px 10px 10px;">
      <a-space style="margin-bottom:10px;">
        <a-button @click="addTable">添加表</a-button>
        <a-button @click="presetFields">表预设字段</a-button>
        <a-button shape="circle" size="small" @click="getTable">
          <template #icon>
            <reload-outlined />
          </template>
        </a-button>
      </a-space>
      <a-input v-model:value="searchTable" size="small" placeholder="搜索表" allow-clear></a-input>
    </div>
    <a-menu mode="inline"  class="curd-table-tree" :selectable="false">
      <a-sub-menu :key="item.id"  v-for="item in tableMenus" @titleClick="onLoadTable(item)">
        <template #title>
          <div @mouseenter="e=>tableMouseenter(e,item)" @mouseleave="e=>tableMouseLeave(e,item)">
            <div class="table-tree-title">
              <FolderOutlined />
              <div class="field-title" :title="item.name">{{ item.name }}</div>
              <div class="table-tree-action-table" v-if="item.mouseenter">
                <a-button shape="circle" size="small" @click.stop="onLoadTable(item)">
                  <template #icon>
                    <reload-outlined />
                  </template>
                </a-button>
                <a-button shape="circle" size="small"  @click.stop="addTableField(item.id)">
                  <template #icon>
                    <PlusOutlined />
                  </template>
                </a-button>

                <a-button shape="circle" size="small" @click.stop="editTable(item.id)">
                  <template #icon>
                    <EditOutlined />
                  </template>
                </a-button>
                <a-button shape="circle" size="small"  @click.stop="relationTable(item.id)">
                  <template #icon>
                    <NodeIndexOutlined />
                  </template>
                </a-button>

                <a-button shape="circle" size="small"  @click.stop="deleteTable(item.id)">
                  <template #icon>
                    <DeleteOutlined />
                  </template>
                </a-button>
              </div>
            </div>
            <div class="field-title-desc" :title="item.comment">{{ item.comment }}</div>
          </div>
        </template>
        <draggable style="width:100%" :list="item.children"
                   @sort="onFieldSort"
                   :clone="method.onClone"
                   @end="method.onEnd"
                   :group="{pull:'clone',put:false}" item-key="id">
          <template #item="{element}">
            <div @mouseenter="e=>tableMouseenter(e,element)" @mouseleave="e=>tableMouseLeave(e,element)">
              <a-menu-item :key="element.id" >

                <div class="table-tree-title">
                  <FileOutlined />
                  <div class="field-title" :title="element.name">{{ element.name }}</div>
                  <div class="table-tree-action" v-if="element.mouseenter">
                    <a-button shape="circle" size="small"
                              @click.stop="editTableField(item.id,element.field,item)">
                      <template #icon>
                        <EditOutlined/>
                      </template>
                    </a-button>
                    <a-button shape="circle" size="small"
                              @click.stop="deleteTableField(item.id,element.field,item)">
                      <template #icon>
                        <DeleteOutlined/>
                      </template>
                    </a-button>
                  </div>
                </div>
                <div class="field-title-desc" :title="element.comment">{{ element.comment }}</div>
              </a-menu-item>
            </div>
          </template>
        </draggable>
      </a-sub-menu>
    </a-menu>
  </div>
</template>

<script>
import {computed, reactive, toRefs, watch} from "vue";
import request from "@/utils/axios";
import {Modal} from "ant-design-vue";
import draggable from 'vuedraggable'
export default {
  name: "CurdDatabase",
  components:{
    draggable
  },
  props:{
    method:Object,
    visible:Boolean,
  },
  setup(props,ctx) {

    const state = reactive({
      tables: [],
      selectedKeys: [],
      searchTable:'',
      tableVisible: false,
      tableModalRender: null,
      tableTreeNode: null,
      tableModalTitle: null,
    })
    watch(()=>state.tableVisible,value=>{
      ctx.emit('update:visible',!value)
    })
    getTable()
    function addTable(){
      state.tableTreeNode = null
      state.tableModalTitle = '添加表'
      state.tableModalRender = null
      request.post('/ex-admin/plugin-curd-controller-Database/tableForm').then(res=>{
        state.tableVisible = true
        state.tableModalRender = res
        state.tableModalRender.footer = res.content.footer[0]
        delete state.tableModalRender.content.footer
      })
    }
    function getTable() {
      request('ex-admin/plugin-curd-controller-Database/getTable').then(res => {
        state.tables = res.data.map(item => {
          item.tableName = item.name
          item.dataRef = item
          item.name = item.id
          item.children = []
          item.class = 'table-tree-node'
          return item
        })
      })
    }
    function onLoadTable(treeNode) {
      state.tableVisible = false
      if(!treeNode){

        getTable()
        return
      }
      return new Promise((resolve) => {
        request('ex-admin/plugin-curd-controller-Database/getTableColumn?table=' + treeNode.dataRef.id).then(res => {
          treeNode.dataRef.children = res.data.map(item => {
            item.id = treeNode.id + item.field
            item.name = item.field
            item.table = treeNode.id
            item.parent = treeNode
            item.isLeaf = true
            return item
          })

          state.tables = [...state.tables];
          resolve();
        })
      });
    }
    function deleteTable(table){
      Modal.confirm({
        title: '删除表',
        content: '确认删除表，不可恢复？',
        onOk() {
          request.delete('/ex-admin/plugin-curd-controller-Database/grid',{
            data:{
              ex_admin_action:'delete',
              ex_admin_sidebar:true,
              ids:[table]
            }
          }).then(res => {
            getTable()
          })
        }
      })
    }
    function deleteTableField(table,field,treeNode){
      Modal.confirm({
        title: '删除表字段',
        content: '确认删除表字段，不可恢复？',
        onOk() {
          request.delete('/ex-admin/plugin-curd-controller-Database/grid',{
            data:{
              ex_admin_action:'delete',
              ex_admin_trashed:'false',
              table:table,
              ids:[field]
            }
          }).then(res => {
            onLoadTable(treeNode)
          })
        }
      })
    }
    function editTableField(table,field,node){
      state.tableTreeNode = node
      state.tableModalTitle = '编辑字段'
      state.tableModalRender = null
      request.put('/ex-admin/plugin-curd-controller-Database/form',{table:table,field:field}).then(res=>{
        state.tableVisible = true
        state.tableModalRender = res
        state.tableModalRender.footer = res.content.footer[0]
        delete state.tableModalRender.content.footer
      })
    }

    function presetFields(){
      state.tableTreeNode = null
      state.tableModalTitle = '表预设字段'
      state.tableModalRender = null
      request.post('/ex-admin/plugin-curd-controller-Database/presetFields').then(res=>{
        state.tableVisible = true
        state.tableModalRender = res
        state.tableModalRender.footer = res.content.footer[0]
        delete state.tableModalRender.content.footer
      })
    }

    function editTable(table){
      state.tableTreeNode = null
      state.tableModalTitle = '编辑表'
      state.tableModalRender = null
      request.post('/ex-admin/plugin-curd-controller-Database/tableForm',{id:table}).then(res=>{
        state.tableVisible = true
        state.tableModalRender = res
        state.tableModalRender.footer = res.content.footer[0]
        delete state.tableModalRender.content.footer
      })
    }

    function relationTable(table){
      state.tableModalTitle = '关联表(模型)'
      state.tableModalRender = null
      request.post('/ex-admin/plugin-curd-controller-Database/modelRelationForm',{table:table}).then(res=>{
        state.tableVisible = true
        state.tableModalRender = res
        state.tableModalRender.footer = res.content.footer[0]
        delete state.tableModalRender.content.footer
      })
    }

    function addTableField(table){
      state.tableModalTitle = '添加表字段'
      state.tableModalRender = null
      request.post('/ex-admin/plugin-curd-controller-Database/form',{table:table}).then(res=>{
        state.tableVisible = true
        state.tableModalRender = res
        state.tableModalRender.footer = res.content.footer[0]
        delete state.tableModalRender.content.footer
      })
    }
    function tableMouseenter(event,node) {
      node.mouseenter = true
      state.tableTreeNode = node
      state.tables = [...state.tables];
    }

    function tableMouseLeave(event,node) {
      node.mouseenter = false
      state.tables = [...state.tables];
    }
    function onFieldSort(e) {
      if(e.newIndex === e.oldIndex) return
      if(e.from === e.to){
        request.post('ex-admin/plugin-curd-controller-Database/sortField',{
          table:e.item.__draggable_context.element.table,
          field:e.item.__draggable_context.element.field,
          sort:e.newIndex,
        })
      }
    }
    const tableMenus = computed(()=>{
      return state.tables.filter(item=>{
        return item.name.indexOf(state.searchTable) > -1 || item.comment.indexOf(state.searchTable) > -1
      })
    })
    function getModalContainer(){
      return document.getElementById('app')
    }
    return {
      getModalContainer,
      tableMenus,
      onFieldSort,
      tableMouseenter,
      tableMouseLeave,
      addTableField,
      editTable,
      relationTable,
      presetFields,
      editTableField,
      deleteTableField,
      deleteTable,
      getTable,
      onLoadTable,
      addTable,
      ...toRefs(state)
    }
  }
}
</script>

<style scoped>
:deep(.curd-table-tree .ant-tree-node-content-wrapper) {
  display: flex;

}
.curd-table-tree{
  overflow-y: auto;
  overflow-x: hidden;
  flex: 1;
  border-right: none;
}

:deep(.ant-menu-item){
  line-height: normal;

}
:deep(.curd-table-tree .ant-menu-title-content){

  align-self: start;
}
:deep(.curd-table-tree .ant-menu-submenu-title){
  line-height: normal;
}
:deep(.curd-table-tree .ant-tree-title) {
  flex: 1;
  width: 220px;
}
.table-tree-action {
  width: 95px;
}
.table-tree-action-table{
  width: 160px;
}
.table-tree-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.flex-column{
  display: flex;
  flex-direction: column;
  height: 100%
}
.field-title {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  flex: 1;
  margin-left: 5px;
}
.field-title-desc {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  flex: 1;
  margin-left: 20px;
  color: #999999;
}
</style>